<?php

class Ev_Controller_Error extends Ev_Controller_Action
{

    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
                // 404 error -- controller not found
                $this->getResponse()->setHttpResponseCode(404);
                $message = $this->view->translate('Controller not found');
                break;
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- action not found
                $this->getResponse()->setHttpResponseCode(404);
                $message = $this->view->translate('Action not found');
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $message = $this->view->translate('Application error');
                break;
        }

        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->crit($this->view->message, $errors->exception);
        }

        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }

        $this->view->request   = $errors->request;

        if ( $this->getRequest()->isXmlHttpRequest() ) {
            $message =  utf8_decode(str_replace("\n", ' ', $message) );
            if( APPLICATION_ENV != 'production' ) {
                $this->getResponse()->setHeader('App-Error-File', $exception->getFile(), true)
                                    ->setHeader('App-Error-Line', $exception->getLine(), true);

            } else {
                $message = $this->view->translate('Application error');
            }
            $message .= ' -> ' . $exception->getMessage();
            $this->getResponse()->setHttpResponseCode(500)
                                ->setHeader('App-Error-Message', $message, true);

        }
        if(APPLICATION_ENV != 'development') {
            try {
                $this->_sendEmail($errors);
            } catch(Exception $e) {
                //Zend_Debug::dump($e);
                //Zend_Mail_Transport_Exception
                // @FIXME ver o que fazer quando der erro no email de email
            }
        }
        $this->view->message   = $message;
    }

    public function getLog()
    {
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasPluginResource('Log')) {
            return false;
        }
        $log = $bootstrap->getResource('Log');
        return $log;
    }

    /**
     * Envia email com o erro
     * @return void
     */
    protected function _sendEmail($errors)
    {
        $titulo = '[APP] Erro [' . APPLICATION_ENV . ']';

        $request = $errors->request;
        $action  = $request->getParam('module') . '/' . $request->getParam('controller') . '/' . $request->getParam('action');

        $corpo  = '<b>' . $errors->exception->getMessage() . '</b><br />';
        $corpo .=  'Action: ' . $action;
        $corpo .= '<br />Erro:';

        ob_start();
        Zend_Debug::dump($errors);
        $conteudo = ob_get_clean();
        ob_end_clean();
        $corpo .= '<br />' . $conteudo;

        $mail = new Zend_Mail('utf-8');
        $mail->setBodyHtml($corpo);
        $mail->setFrom('erros@estradavirtual.com.br', 'Estrada Virtual');
        $mail->addTo('erros@estradavirtual.com.br');
        $mail->setSubject($titulo);
        $mail->send();
    }
}
